package cn.kgc.vue.controller;

import cn.kgc.vue.common.ResponseResult;
import cn.kgc.vue.common.ResponseStatus;
import cn.kgc.vue.entity.User;
import cn.kgc.vue.form.PasswordForm;
import cn.kgc.vue.form.UserLoginForm;
import cn.kgc.vue.service.UserService;
import cn.kgc.vue.utils.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/8/8
 * @Description:
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    ResponseResult responseResult = new ResponseResult();

    @PostMapping("login")
    public ResponseResult login(@RequestBody UserLoginForm userLoginForm){

        return userService.login(userLoginForm);
    }

    //获取用户信息
    @GetMapping("userinfor")
    public ResponseResult infor(HttpServletRequest request){
        String token = request.getHeader("token");
        Map<String, Object> claim = JWTUtil.getClaim(token);
        Integer userId = (Integer) claim.get("userId");
        User user = userService.getById(userId);
        responseResult.success(ResponseStatus.SUCCESS,user);
        return responseResult;
    }
   //更新用户信息
    @PutMapping("updateinfor")
    public ResponseResult update(@RequestBody User user){
        userService.updateById(user);
        responseResult.success();
        return responseResult;
    }

    //更新密码
    @PutMapping("updatepassword")
    public ResponseResult updatepassword(@RequestBody PasswordForm passwordForm,HttpServletRequest request){
        String token = request.getHeader("token");
        Map<String, Object> claim = JWTUtil.getClaim(token);
        Integer userId = (Integer) claim.get("userId");
        User user = userService.getById(userId);
        String password = user.getPassword();
        String oldPassword = passwordForm.getOldPassword();
        oldPassword=new Md5Hash(oldPassword,user.getSalt(),1024).toString();
        if(!StringUtils.equals(password,oldPassword)){
            throw new IncorrectCredentialsException();
        }
        //然后修改
        String newPassword = passwordForm.getNewPassword();
        newPassword=new Md5Hash(newPassword,user.getSalt(),1024).toString();

        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getId,userId).set(User::getPassword,newPassword);
        userService.update(wrapper);
        responseResult.success();
        return responseResult;
    }


}
